﻿package  {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class Scores extends MovieClip {
		static public const USER_SCORES = 1296;
		static public const NEXT_LEVEL = 6000;
		private var main: Main = null;
		
		function Scores() {
			main = Main(root);
			main.scores = this;
			
			main.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
		
		function onAddedToStage(e: Event):void {
			//TODO score loads
			scores = 0;
			loadScores();
		}
		
		public function get scores(): Number {
			return _scores > 0? _scores: 0;
		}
		
		public function set scores(newScores: Number): void {
			_scores = newScores;
			labelScores.text = "" + _scores;
			
			if (_scores > _hiUserScore) {
				_hiUserScore = _scores;
				upload();
			}
			
			if (_scores > main.level.level * NEXT_LEVEL) {
				main.level.level ++;
			}
		}
		
		private function upload() {
			main.vKontakte.api("putVariable", { key: USER_SCORES, value: ""+_scores, user_id: main.viewerID}, _uploadOk, _uploadError);
		}
		
		private function _uploadOk(e: Object) {	//Empty
			trace(e);
		}
		
		private function _uploadError(e: Object) {
			trace("Error: ", e);
		}
		
		private function download(e: Object): void {
			_hiUserScore = Number(e);
		}
		
		private function onErrorLoadScores( e: Object):void {
			loadScores();
		}
		public function loadScores(): void {
			main.vKontakte.api("getVariable", { key: USER_SCORES, user_id: main.viewerID}, download, onErrorLoadScores);
		}
		protected var _scores: Number = 0;
		protected var _hiUserScore: Number = 0;
	}
	
}
